package handler

import (
	"common"
	"common/biz"
	"common/logs"
	"context"
	"core/models/entity"
	"core/repo"
	"core/service"
	"encoding/json"
	"framework/remote"
	"hall/logic"
	"hall/models/request"
	"hall/models/response"
	"strconv"
)

type MarketHandler struct {
	marketService *service.MarketService
	userService   *service.UserService
	walletService *service.WalletService
	base          *BaseHandler
	marketM       *logic.MarketManager
}

func (m *MarketHandler) MarketSell(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketList msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketSell err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketSell
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketSell err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	user, err := m.userService.FindUserByUid(ctx, uint(uid))
	if err != nil {
		logs.Error("[marketHandler]用户%d MarketSell err:缺少参数 req=%v,dbErr=%v", uid, req, err)
		return common.F(biz.SqlError)
	}
	errs := m.base.Check(user)
	if errs != nil {
		return common.F(errs)
	}
	data := new(entity.TradeSellLog)
	data, errs = m.marketService.MarketSell(ctx, uint(uid), &req)
	if errs != nil {
		return common.F(errs)
	}
	return common.S(data)
}

func (m *MarketHandler) MarketList(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketList msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketList err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketSearch
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketList err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	user, err := m.userService.FindUserByUid(ctx, uint(uid))
	if err != nil {
		logs.Error("[marketHandler]用户%d MarketList err:获取用户数据失败 req=%v,dbErr=%v", uid, req, err)
		return common.F(biz.SqlError)
	}
	errs := m.base.Check(user)
	if errs != nil {
		return common.F(errs)
	}
	// 将用户写入
	m.marketM.UserWrite(req.Type, user)
	count, trade := m.marketService.MarketSellList(ctx, &req, uint(uid))
	return common.S(response.TradeSellAll{
		Count: count,
		List:  trade,
	})
}

func (m *MarketHandler) MarketBuy(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketBuy msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketBuy err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketBuy
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketBuy err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	user, err := m.userService.FindUserByUid(ctx, uint(uid))
	if err != nil {
		logs.Error("[marketHandler]用户%d MarketList err:获取用户数据失败 req=%v,dbErr=%v", uid, req, err)
		return common.F(biz.SqlError)
	}
	errs := m.base.Check(user)
	if errs != nil {
		return common.F(errs)
	}
	order, errs := m.marketM.CreateOrder(ctx, uint(uid), &req, session)
	if errs != nil {
		return common.F(errs)
	}
	return common.S(order)
}

func (m *MarketHandler) MarketPay(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketPay msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketPay err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketOrderNo
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketPay err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	userData, errs := m.userService.FindUserByUid(ctx, uint(uid))
	if errs != nil {
		logs.Error("[marketHandler]用户%d MarketPay err:获取用户数据失败 req=%v,dbErr=%v", uid, req, errs)
		return common.F(biz.RequestDataError)
	}
	// 数据检验
	err := m.base.Check(userData)
	if err != nil {
		return common.F(err)
	}
	payUrl, err := m.marketM.OrderPay(uint(uid), req.OrderNo)
	if err != nil {
		return common.F(err)
	}
	return common.S(map[string]any{
		"payUrl": payUrl,
	})
}

func (m *MarketHandler) MarketSellList(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketSellList msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketSellList err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.PageMsg
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketSellList err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	trade := new([]response.TradeMySellList)
	var count int64
	count, trade = m.marketService.MarketMySellList(ctx, &req, uint(uid))
	return common.S(response.TradeMySellAll{
		Count: count,
		List:  trade,
	})
}

func (m *MarketHandler) MarketSellWithdraw(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketSellWithdraw msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketSellWithdraw err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.CommonID
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketSellWithdraw err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	data, err := m.marketService.MarketSellWithdraw(ctx, uint(uid), &req)
	if err != nil {
		return common.F(err)
	}
	return common.S(data)
}

func (m *MarketHandler) MarketBuyList(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketBuyList msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketBuyList err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketBuySearch
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketBuyList err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	trade := new([]entity.MarketOrder)
	var count int64
	count, trade = m.marketService.MarketMyBuyList(ctx, uint(uid), &req)
	return common.S(response.TradeMyBuyAll{
		Count: count,
		List:  trade,
	})
}

func (m *MarketHandler) MarketCancel(session *remote.Session, msg []byte) any {
	logs.Info("[marketHandler] MarketCancel msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[marketHandler] MarketCancel err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := m.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.MarketOrderNo
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[marketHandler]用户%d MarketCancel err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	//orderData := req.OrderNo[6:14]
	//hfResult, errs := m.walletService.OrderQueryWallet(req.OrderNo, orderData)
	//if errs != nil {
	//	logs.Error("[marketHandler]用户%d MarketCancel err:查询汇付是否支付错误 req=%v,err=%v", uid, req, errs)
	//	return common.F(biz.RequestDataError)
	//}
	//if hfResult.TransStat == "S" {
	//	return common.F(biz.CancelError)
	//} else {
	//	data, err := m.marketService.MarketCancel(ctx, uint(uid), req.OrderNo)
	//	if err != nil {
	//		return common.F(err)
	//	}
	//	return common.S(data)
	//}
	data, err := m.marketService.MarketCancel(ctx, uint(uid), req.OrderNo)
	if err != nil {
		return common.F(err)
	}
	return common.S(data)
}

func NewMarketHandler(r *repo.Manager, marketM *logic.MarketManager) *MarketHandler {
	return &MarketHandler{
		marketService: service.NewMarketService(r),
		userService:   service.NewUserService(r),
		walletService: service.NewWalletService(r),
		base:          NewBaseHandler(r),
		marketM:       marketM,
	}
}
